package top.dancun.easuser.controller;

import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import top.dancun.common.entity.UserEntity;
import top.dancun.common.utils.R;
import top.dancun.easuser.form.LoginForm;
import top.dancun.easuser.service.CaptchaService;
import top.dancun.easuser.service.UserService;
import top.dancun.easuser.service.UserTokenService;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

@RestController
public class LoginConntroller extends AbstractController{
    @Autowired
    private UserService userService;
    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private CaptchaService captchaService;

    /**
     * 验证码
     */
    @GetMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = captchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    /**
     * 登录
     */
    @PostMapping("/sys/login")
    public Map<String, Object> login(@RequestBody LoginForm form)throws IOException {
        boolean captcha = captchaService.validate(form.getUuid(), form.getCaptcha());
        if(!captcha){
            return R.error("验证码不正确");
        }

        //用户信息
        UserEntity user = userService.queryByUserName(form.getUsername());

        //账号不存在、密码错误
        if(user == null || !user.getPwd().equals(new Sha256Hash(form.getPassword(), user.getUid().toString()).toHex())) {
            return R.error("账号或密码不正确");
        }

        //账号锁定
        if(user.getStatus() == 0){
            return R.error("账号已被锁定,请联系管理员");
        }

        //生成token，并保存到数据库
        R r = userTokenService.createToken(user.getUid());
        return r;
    }

    /**
     * 注册
     */
    @PostMapping("/sys/register")
    public Map<String, Object> register(@RequestBody LoginForm form)throws IOException {
        boolean captcha = captchaService.validate(form.getUuid(), form.getCaptcha());
        if(!captcha){
            return R.error("验证码不正确");
        }
        UserEntity user = userService.lambdaQuery().eq(UserEntity::getUid,form.getUsername()).one();
        if (user!=null){
            return R.error("账号已存在");
        }
        //用户信息
        userService.register(form);

        //生成token，并保存到数据库
        R r = userTokenService.createToken(form.getUsername());
        return r;
    }

    /**
     * 退出
     */
    @PostMapping("/sys/logout")
    public R logout() {
        userTokenService.logout(getUserId());
        return R.ok();
    }
}
